package com.jiazhong.example.example.rocket.demo1.alipay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.jiazhong.example.example.rocket.demo1.alipay.listener.AlipayOrderListener;
import com.jiazhong.example.example.rocket.demo1.alipay.service.AlipayService;
import com.jiazhong.example.example.rocket.demo1.commons.bean.Alipay;
import com.jiazhong.example.example.rocket.demo1.commons.bean.Book;
import com.jiazhong.example.example.rocket.demo1.commons.bean.Order;
import com.jiazhong.example.example.rocket.demo1.commons.mapper.BookMapper;
import com.jiazhong.example.example.rocket.demo1.commons.mapper.OrderMapper;
import com.jiazhong.example.example.rocket.demo1.commons.util.JsonResult;
import com.jiazhong.example.example.rocket.demo1.commons.util.ResultTool;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.text.NumberFormat;

@Slf4j
@Service
public class AlipayServiceImpl implements AlipayService {
    @Value("${appId}")
    private String appId;
    @Value("${privateKey}")
    private String privateKey;
    @Value("${publicKey}")
    private String publicKey;
    @Value("${notifyUrl}")
    private String notifyUrl;
    @Value("${returnUrl}")
    private String returnUrl;
    @Value("${signType}")
    private String signType;
    @Value("${charset}")
    private String charset;
    @Value("${gatewayUrl}")
    private String gatewayUrl;

    @Resource
    private AlipayOrderListener alipayOrderListener;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private BookMapper bookMapper;

    @SneakyThrows
    @Override
    public String pay(Alipay alipay) {
        // 1. 生成订单
        // 获取到图书的单价
        Book book = bookMapper.selectById(alipay.getBookId());
        NumberFormat numberFormat = new DecimalFormat("0.00");
        String format = numberFormat.format(alipay.getNumber() * book.getPrice());
        alipay.setTotal_amount(Double.parseDouble(format));
        // 录入一笔订单
        Order order = new Order();
        order.setId(alipay.getOut_trade_no());
        order.setBookId(alipay.getBookId());
        order.setNumber(alipay.getNumber());
        order.setPrice(alipay.getTotal_amount());
        order.setStatus(1);
        log.info("order:{}", order);
        orderMapper.insert(order);

        // 2. 产生支付宝的客户端
        AlipayClient client = new DefaultAlipayClient(gatewayUrl, appId, privateKey,
                "json", charset, publicKey, signType);
        // 产生交易对象
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 设置回调
        request.setReturnUrl(returnUrl);
        request.setNotifyUrl(notifyUrl);
        // 设置支付参数
        String s = JSONArray.toJSONString(alipay);
        request.setBizContent(s);
        // 执行
        return client.pageExecute(request).getBody();
    }

    @SneakyThrows
    @Override
    public JsonResult query(Alipay alipay) {
        AlipayClient client = new DefaultAlipayClient(gatewayUrl, appId, privateKey,
                "json", charset, publicKey, signType);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent(JSONArray.toJSONString(alipay));
        AlipayTradeQueryResponse response = client.execute(request);
        String tradeStatus = response.getTradeStatus();
        log.info("tradeStatus:{}", tradeStatus);
        // 如果支付成功了，向rocketMQ发送一个半事务消息
        if (tradeStatus.contains("SUCCESS")) {
            this.sendTransactionMessage(alipay);
        }

        return ResultTool.success(tradeStatus);
    }

    @SneakyThrows
    private void sendTransactionMessage(Alipay alipay) {
        TransactionMQProducer producer = new TransactionMQProducer("transaction_order_a");
        producer.setNamesrvAddr("124.220.170.254:9876");
        producer.setTransactionListener(alipayOrderListener);
        producer.start();
        String topic = "Order";
        String tags = "alipay";
        String body = JSON.toJSONString(alipay);
        Message message = new Message(topic, tags, body.getBytes(StandardCharsets.UTF_8));
        producer.sendMessageInTransaction(message, null);
    }
}
